/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Course;
import org.hibernate.Session;
import service.CourseDao;
import service.HibernateUtil;

/**
 *
 * @author Aster
 */
public class CourseDescriptionController extends HttpServlet {

    HibernateUtil HU = new HibernateUtil();
    Session session = HU.openSession();
    CourseDao cdao = new CourseDao(session);

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        Long id = Long.parseLong(request.getParameter("id"));
        Course course = cdao.get(id);
        request.setAttribute("descriptionCourse", course);
        
        HttpSession sessie = request.getSession(true);
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("status")) {
                if (cookie.getValue().equals("Tutor")||cookie.getValue().equals("Admin")) {
                    forward(request, response, "tutorcourseDescription.jsp");
                }else if(cookie.getValue().equals("Student")){
                    forward(request, response, "studentcourseinfo.jsp");
                }
            }
        }   
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        Long id = Long.parseLong(request.getParameter("id"));
        Course course = cdao.get(id);
        course.setDescription(request.getParameter("content"));
        course.setLongDescription(request.getParameter("content2"));
        cdao.save(course);
        request.setAttribute("descriptionCourse", course);
        
        forward(request, response, "tutorcourseDescription.jsp");
    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String url)
            throws ServletException, IOException {

        String address = "/"+url;
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
}
